const lessWork = require("../models/lessWork");
const { setJson, deleteEmpty } = require("../utils/index");
// 获取用户作品
exports.getWorkList = (req, res, next) => {
  const { query: { userId, id } } = req;
  const params = deleteEmpty({ userId, _id: id })
  lessWork
    .find(params)
    .then(data => setJson(res, 200, "success", data))
    .catch(error => setJson(res, 0, "查询失败", error))
}
// 保存作品
exports.createWork = (req, res, next) => {
  const { body: { userId, type, width, height, canvasBg, imgUrl, components, name } } = req;
  if(!userId) return setJson(res, 400, "参数错误：缺少userId", null);
  if(!components.length) return setJson(res, 400, "参数错误：不能保存空画布", null);
  const params = { userId, type, width, height, canvasBg, imgUrl, components, name }
  lessWork
    .create(params)
    .then(data => setJson(res, 200, "success", data))
    .catch(error => setJson(res, 0, "保存失败", error))
}
// 更新作品
exports.updateWork = (req, res, next) => {
  const { body: { userId, type, width, height, canvasBg, imgUrl, components, _id } } = req;
  if(!userId) return setJson(res, 400, "参数错误：缺少userId", null);
  if(!components.length) return setJson(res, 400, "参数错误：不能保存空画布", null);
  const params = { type, width, height, canvasBg, imgUrl, components }
  lessWork.findOneAndUpdate({ _id, userId}, params)
    .then(data => setJson(res, 200, "success", data))
    .catch(error => setJson(res, 0, "更新失败", error))
}
// 删除作品
exports.deleteWork = (req, res, next) => {
  const { query: { userId, id } } = req;
  const params = deleteEmpty({ userId, _id: id })
  lessWork
    .deleteOne(params)
    .then(data => setJson(res, 200, "success", data))
    .catch(error => setJson(res, 0, "查询失败", error))
}